import React, { FC } from 'react';
import { FormInstance } from 'antd/lib/form';
import { Row, Col, Spin } from 'antd';
import ProTable, { ProColumns } from '@/components/ProTable';
import useHoxModel from '@/pages/Users/useHoxModel';
import { AddUserTypeReturnType, AreaListReturnProps } from '../../../../API';
import { useUnmount, useUpdateEffect } from 'ahooks';
import styles from './index.less';
import AddUpload from './AddUpload';
import { pick } from 'lodash';
import arrayToTree from '@/pages/DoorGroup/components/DoorTable/components/Modal/arrayToTree';

const AddForm: FC<{
  photoRef: React.MutableRefObject<FormInstance | undefined>;
  rightRef: React.MutableRefObject<FormInstance | undefined>;
  bottomRef: React.MutableRefObject<FormInstance | undefined>;
}> = ({ photoRef, rightRef, bottomRef }) => {
  const {
    userFormAreaList = [],
    getFormAreaList,
    dispatch,
    userInfo = {},
    userInfoLoading,
  } = useHoxModel((model) => [model.userFormAreaList, model.userInfo, model.userInfoLoading]);
  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    let res = await getFormAreaList({ id: targetOption.value });
    if (res.result === 0) {
      targetOption.loading = false;
      targetOption.children = res?.data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          isLeaf: item.isRegion,
        };
      });
      dispatch({ userFormAreaList: [...userFormAreaList] });
    }
  };
  useUnmount(() => {
    photoRef.current?.resetFields();
    rightRef.current?.resetFields();
    bottomRef.current?.resetFields();
  });

  useUpdateEffect(() => {
    if (JSON.stringify(userInfo) !== '{}') {
      photoRef.current?.setFieldsValue({ photo: userInfo.photo });
      const rightData = pick(userInfo, ['name', 'userName', 'phone']);
      rightRef.current?.setFieldsValue(rightData);
      const bottomData = pick(userInfo, ['idCard', 'areas', 'rec']);

      bottomRef.current?.setFieldsValue({
        ...bottomData,
        areas:
          userInfo.areaPath.map((item: AreaListReturnProps) => {
            return item.id;
          }) || [],
      });
      let currentAreaList = arrayToTree(userInfo.areaPath);
      dispatch({ userFormAreaList: currentAreaList });
    }
  }, [userInfo]);

  const columns: ProColumns<AddUserTypeReturnType>[] = [
    {
      title: '姓名:',
      dataIndex: 'name',
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '用户名称:',
      dataIndex: 'userName',
      rules: [
        {
          required: true,
        },
      ],
    },
    // {
    //   title: '密码:',
    //   dataIndex: 'passWord',
    //   valueType: 'password',
    //   formItemProps: {
    //     disabled: isEdit ? true : false,
    //   },
    //   rules: [
    //     {
    //       required: true,
    //     },
    //   ],
    // },
    {
      title: '手机号码:',
      dataIndex: 'phone',
      rules: [
        {
          required: true,
        },
        {
          pattern: /^(?:(?:\+|00)86)?1\d{10}$/,
          message: '请输入正确的手机号码！',
        },
      ],
    },
  ];
  const columns1: ProColumns<AddUserTypeReturnType>[] = [
    {
      title: '身份证号码:',
      colItemSpan: 12,
      dataIndex: 'idCard',
      rules: [
        {
          required: true,
        },
        {
          pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
          message: '请输入正确的身份证号码！',
        },
      ],
    },
    {
      title: '所属区域:',
      dataIndex: 'areas',
      colItemSpan: 12,
      valueType: 'cascader',
      formItemProps: {
        options: userFormAreaList,
        loadData,
        changeOnSelect: true,
      },
      rules: [
        {
          required: true,
        },
      ],
    },
    {
      title: '备注:',
      dataIndex: 'rec',
      valueType: 'textarea',
    },
  ];

  return (
    <Spin spinning={userInfoLoading}>
      <Row gutter={16} className={styles['add-form']}>
        <Col span={12}>
          <ProTable<AddUserTypeReturnType>
            form={{ layout: 'vertical', autoComplete: 'off', initialValues: { photo: '' } }}
            columns={[
              {
                title: '用户肖像:',
                dataIndex: 'photo',
                renderFormItem: () => <AddUpload formRef={photoRef} />,
              },
            ]}
            type={'form'}
            formRef={photoRef}
          />
        </Col>
        <Col span={12} className={styles['add-form-right']}>
          <ProTable<AddUserTypeReturnType>
            form={{ layout: 'vertical', autoComplete: 'off' }}
            columns={columns}
            type={'form'}
            formRef={rightRef}
          />
        </Col>
      </Row>
      <ProTable<AddUserTypeReturnType>
        form={{ layout: 'vertical', autoComplete: 'off', initialValues: { name: '' } }}
        columns={columns1}
        type={'form'}
        formRef={bottomRef}
      />
    </Spin>
  );
};
export default AddForm;
